package control;

import entity.Dept;
import entity.Meeting;
import entity.PageEntity;
import entity.User;
import service.ListService;
import service.MeetingService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/meeting/*")
public class MeetingServlet extends BaseServlet {
    private MeetingService meetingService = new MeetingService();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 参加会议
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     * @throws ParseException
     */
    public void joinMeeting(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, ParseException {
        Map<String, String> param = getParam(req);

        Long meetingId = Long.parseLong(param.get("meetingId"));

        // 根据userId和meetingId查询是否参加过此次会议
        Integer flag = meetingService.countByUserIdAndMeetingId(loginUser.getId(), meetingId);

        if (flag > 0) {
            // 我已经参加过此次会议,我是来取消会议的
            meetingService.unJoinMeeting(loginUser.getId(), meetingId);

        } else {

            // 我没有参加过此次会议,我是来参加会议的
            meetingService.joinMeeting(loginUser.getId(), meetingId);
        }

        // 刷新页面
        resp.sendRedirect("/meeting/meetingDetail?meetingId=" + meetingId);
    }

    /**
     * 查询会议详情
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void meetingDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Map<String, String> param = getParam(request);

        long meetingId = Long.parseLong(param.get("meetingId"));
        Meeting meeting = meetingService.findById(meetingId);

        Integer joinUser = 1;

        if (meeting.getMakeUser().length() != 1){
            //应道人数
            joinUser = meeting.getMakeUser().split(",").length;
        }

        // 实到人数
        Integer realCount = meetingService.countJoinMeetingByMeetingId(meetingId);

        // 未到人数
        Integer noCount = joinUser  - realCount;

        // 我是否有参加过这个会议
        Boolean isJoinMeeting = meetingService.isJoinMeeting(loginUser.getId(), meetingId);

        //我是否可以操作本次会议
        List<String> ids = Arrays.asList(meeting.getMakeUser().split(","));
        Boolean isJoin = ids.contains(loginUser.getId()+"");

        request.setAttribute("meeting", meeting);
        request.setAttribute("joinCount", joinUser);
        request.setAttribute("realCount", realCount);
        request.setAttribute("noCount", noCount);
        request.setAttribute("isJoinMeeting", isJoinMeeting);
        request.setAttribute("isJoin", isJoin);

        request.getRequestDispatcher("/html/meeting_detail.jsp").forward(request, response);

    }

    /**
     * 发布会议
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void issue(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            Map<String, String> param = getParam(request);

            String title = param.get("title");
            Long deptId = Long.parseLong(param.get("deptId"));
            String makeUser = param.get("makeUser");
            String startTime = param.get("startTime");
            String endTime = param.get("endTime");
            String content = param.get("content");

            //根据部门id查询部门名称
            String deptName = meetingService.findBydeptName(deptId);

            Meeting meeting = new Meeting();

            meeting.setDeptName(deptName);
            meeting.setDeptId(deptId);
            meeting.setTitle(title);
            meeting.setContent(content);
            meeting.setStartTime(sdf.parse(startTime));
            meeting.setEndTime(sdf.parse(endTime));

            if (makeUser.startsWith("[")) {
                //代表抄送了多个用户
                makeUser = makeUser.substring(1);
                makeUser = makeUser.substring(0, makeUser.length() - 1);
                makeUser = makeUser.replaceAll(" ", "");
            }

            meeting.setMakeUser(makeUser);
            meeting.setPublishDate(new Date());
            meeting.setStatus(0L);

            //将新建会议插入数据库
            meetingService.insertMeeting(meeting);

            //再去会议页面
            response.sendRedirect("/meeting/meetings?currPage=1");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据部门查询下面对应的员工
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void findByUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Map<String, String> param = getParam(request);
        Integer deptId = Integer.parseInt(param.get("deptId"));

        List<User> userList = meetingService.findByUser(deptId);

        request.setAttribute("userList", userList);

        // 转成Json写到前端
        writerObjToString(response, userList);
    }

    /**
     * 查询所有部门和下面的员工，联动
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void deptAndName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        //查询所有的部门
        List<Dept> deptList = meetingService.findBydept();

        request.setAttribute("deptList", deptList);

        // 转成Json写到前端
        writerObjToString(response, deptList);

    }

    /**
     * 会议分页+搜索分页
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void meetings(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PageEntity<Meeting> meetingPageEntity = new PageEntity<>();
        Map<String, String> param = getParam(request);
        //当前页
        Integer currPage = Integer.parseInt(param.get("currPage"));
        //搜索条件
        String title = param.get("title");
        //会议状态
        String status = param.get("status");
        if ("-1".equals(status) || "".equals(status)) {
            //前端没有选取会议状态
            meetingPageEntity = meetingService.findPage(title, currPage);
        } else {
            Long statusL = Long.parseLong(status);
            meetingPageEntity = meetingService.findPageS(title, currPage, statusL);
        }
        request.setAttribute("meetingPageEntity", meetingPageEntity);
        request.setAttribute("title", title);
        request.setAttribute("status", status);

        request.getRequestDispatcher("/html/meeting.jsp").forward(request, response);
    }

}
